<template>
  <div class="hello">
    <el-upload
      class="upload-demo"
      drag
      action="http://up-z2.qiniup.com"
      :data="uploadData"
      :multiple="false"
      :before-upload="uploadVideoBefore"
      :http-request="upfile"
    >
                <i class="el-icon-upload"></i>          
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
               
      <div class="el-upload__tip">
                    上传视频接口，只有当出现绿色的√的时候才表示成功          
      </div>
    </el-upload>
    <el-progress
      v-if="progressFlag"
      :text-inside="true"
      :stroke-width="20"
      :percentage="percentage"
    ></el-progress
    > 
  </div>
</template>

<script>
import * as qiniu from "qiniu-js";
import axios from "axios";
import { getUUID, getCurrentDate } from "../../static/js/uuid";
export default {
  data() {
    return {
      uploadData: {
        token: "",
        key: "",
      },
      percentage: 0,
      progressFlag: false,
    };
  },
  methods: {
    uploadVideoBefore(file) {
      //文件名初始化
      const fullFileName = getCurrentDate()+"/"+file.size+file.name;
      this.uploadData.key = fullFileName;
    },
    upfile(param) {
      /**
       * 上传时候打开进度条，给进度条初始化值为0;
       * percentage 进度条值
       * progressFlag 是否开启
       */
      this.percentage = 0;
      this.progressFlag = true;
      /**
       * 配置上传config
       * useCdnDomain 是否使用cdn加速域名
       * region 选择上传域名区域
       * domain 七牛云域名
       * chunkSize 切片大小 默认为3m
       * forceDirect true=直传 false=切片
       */
      var config = {
        useCdnDomain: true, 
        region: qiniu.region.z2,
        domain: "http://cdn.xxxxx.com", 
        chunkSize: 10, 
        forceDirect: false, 
      };
      /**
       * 忘记是啥，没这个还不行↓
       */
      var putExtra = {
        fname: "",
        params: {},
        mimeType: null,
      };
      /**
       * 组装参数
       * */ 
      var key = this.uploadData.key;
      let token = localStorage.getItem("uptoken");
      /**
       * 调用上传API
       */ 
      var observable = qiniu.upload(param.file, key, token, putExtra, config);
      observable.subscribe({
        next: (result) => {
          //展示进度
          //进度条控件赋值
          this.percentage = result.total.percent.toFixed(2);
        },
        error: (err) => {
          //上传错误后触发
          console.log(err);
          param.onError();
        },
        complete: (result) => {
          //上传成功后触发。返回文件Key和hash
          let key = result.key
          //拼接url 保存入库
          let url = "http://cdn.xxxxx.com/"+key
          console.log(url);
          //入库操作
          /**
           * 省略与后端交互请求
           * 
          */
          //触发控件onSuccess()事件,控件自带;
          param.onSuccess();
          //一秒后隐藏进度条
          setTimeout(() => {
            this.progressFlag = false;
          }, 1000);
        },
      });
    },
    /**
     * 获得本地存储空间localStorage中的uptoken信息
     * 如果没有信息 就去发送获取token请求 写入localStorage
     */
    localuptoken() {
      let uptoken = localStorage.getItem("uptoken");
      console.log("localuptoken()"+uptoken);
      let createtime = localStorage.getItem("createtime");
      if (!uptoken || !createtime) {
       this.getToken();
      } else {
        let unixtime = Math.round(new Date() / 1000);
        let createtime = localStorage.getItem("createtime");
        console.log(createtime);
        console.log(unixtime);
        if(unixtime-createtime>21600){
          this.getToken();
        }
      }
    },
    /**获取token */
    async getToken(){
      await axios.get("http://localhost:8111/qiniu/gettoken").then((res) => {
          localStorage.setItem("createtime", res.data.createtime);
          localStorage.setItem("uptoken", res.data.token);
        });
    }
  },
  mounted() {
    this.localuptoken()
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
